//
//  RechargeViewController.m
//  Molian
//
//  Created by wansong on 4/9/15.
//  Copyright (c) 2015 xiaocan. All rights reserved.
//

#import "RechargeViewController.h"

#import <IAPShare.h>
#import "NSData+Base64.h"

@interface RechargeViewController ()

@property (nonatomic, strong) NSMutableArray *rechargeBtnArray;

@property NSUInteger selectedRechargeIndex;

@property NSArray *productIdentifiers;

@property NSArray *rechargeMoneys;
@end

@implementation RechargeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"充值";
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    // 从导航条以下开始计算
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    // 默认选中6元
    self.selectedRechargeIndex = 0;
    
    self.productIdentifiers = @[IAP_ID_6_YUAN, IAP_ID_18_YUAN, IAP_ID_30_YUAN, IAP_ID_60_YUAN, IAP_ID_108_YUAN, IAP_ID_488_YUAN];
    self.rechargeMoneys = @[@6, @18, @30, @60, @108, @488];
    
    // 广告图片
//    UIImageView *adsImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DeviceWidth, 100)];
//    [adsImgView setContentMode:UIViewContentModeScaleAspectFill];
//    adsImgView.image = [UIImage imageNamed:@"top_chongzhi_image"];
//    [self.view addSubview:adsImgView];
    
    
    NSArray *rechargeNums = @[@"  ¥ 6", @"  ¥ 18", @"  ¥ 30", @"  ¥ 60", @"  ¥ 108",@"  ¥ 488"];
    self.rechargeBtnArray = [[NSMutableArray alloc]init];
    for (int i = 0; i<6; i++) {
        int startHeight;
        int x = i % 3;
        if (i < 3) {
            startHeight = 40;
        } else {
            startHeight = 106;
        }
        UIButton *moneyBtn = [[UIButton alloc]initWithFrame:CGRectMake((5 * x + 1) * DeviceWidth / 16, startHeight, (DeviceWidth/4), 36)];
        [moneyBtn setBackgroundImage:[UIImage imageWithColor:RGBA(230, 228, 233, 1)] forState:UIControlStateNormal];
        [moneyBtn setBackgroundImage:[UIImage imageWithColor:APPCOLOR(1)] forState:UIControlStateSelected];
        [moneyBtn setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
        [moneyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [moneyBtn.layer setCornerRadius:18];
        moneyBtn.layer.masksToBounds = YES;//开启圆角
        [moneyBtn setTitle:rechargeNums[i] forState:UIControlStateNormal];
        moneyBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        moneyBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [moneyBtn setImage:[UIImage imageNamed:@"gold_icon"] forState:UIControlStateNormal];
        moneyBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [moneyBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
        moneyBtn.tag = i;
        [moneyBtn addTarget:self action:@selector(selectRechargeType:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:moneyBtn];
        [self.rechargeBtnArray addObject:moneyBtn];
    }
    // 默认选中第一个
    UIButton *firstBtn = self.rechargeBtnArray[0];
    firstBtn.selected = YES;
    
    // 充值按钮
    UIButton *rechargeBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 200, DeviceWidth-30, 45)];
    rechargeBtn.layer.masksToBounds = YES;
    [rechargeBtn.layer setCornerRadius:22.5f];
    [rechargeBtn setBackgroundImage:[UIImage imageWithColor:RGBA(87, 221, 121, 1)] forState:UIControlStateNormal];
    [rechargeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rechargeBtn setTitle:@"马上支付" forState:UIControlStateNormal];
    rechargeBtn.titleLabel.font = [UIFont fontWithName:FontName size:16];
    [rechargeBtn addTarget:self action:@selector(rechargeMoneyAtIndex:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rechargeBtn];
    
    // 初始化IAP
    if (![IAPShare sharedHelper].iap.products) {
        [self initIAP];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

#pragma mark - init IAP
// 初始化内购
- (void)initIAP {
    if(![IAPShare sharedHelper].iap) {
        NSSet *dataSet = [[NSSet alloc]initWithArray:self.productIdentifiers];
        [IAPShare sharedHelper].iap = [[IAPHelper alloc] initWithProductIdentifiers:dataSet];
    }
    [HUD setOnViewWithTitle:@"" animated:YES];

    [IAPShare sharedHelper].iap.production = NO;
    [[IAPShare sharedHelper].iap requestProductsWithCompletion:^(SKProductsRequest *request,SKProductsResponse *response)
     {
         [HUD hideFromViewAnimated:YES];
         if (response > 0) {
             NSLog(@"get products succeed");
         } else {
             NSLog(@"get products faild");
             [HUD Prompt:@"支付项加载失败,请退出页面再重试"];
         }
     }];
}


#pragma mark user interaction

// 选择充值金额
- (void)selectRechargeType:(UIButton *)sender{
    UIButton *oldBtn = self.rechargeBtnArray[self.selectedRechargeIndex];
    oldBtn.backgroundColor = UIColorFromRGB(0xeeeeee);
    oldBtn.selected = NO;
    
    sender.selected = YES;
    self.selectedRechargeIndex = [self.rechargeBtnArray indexOfObject:sender];
}

// 执行充值
- (void)rechargeMoneyAtIndex:(UIButton *)sender {
    /*
    if ([MobClick isJailbroken]) {
        [HUD Prompt:@"越狱设备当前不支持该方式充值"];
        return;
    }
     */
    
    // 执行充值
    IAPHelper *iap = [IAPShare sharedHelper].iap;
    NSArray *products = iap.products;
    if (!products || [products count] == 0) {
        [HUD Prompt:@"支付项加载失败,请退出页面再重试"];
        return;
    }
    // 找到指定的product
    NSString *identifier = self.productIdentifiers[self.selectedRechargeIndex];
    NSString *rechargeMoney = self.rechargeMoneys[self.selectedRechargeIndex];
    SKProduct *selectProduct;
    for (SKProduct *product in products) {
        if ([product.productIdentifier isEqualToString:identifier]) {
            selectProduct = product;
            break;
        }
    }
    [HUD setOnViewWithTitle:@"正在交易..." animated:YES];
    [[IAPShare sharedHelper].iap buyProduct:selectProduct onCompletion:^(SKPaymentTransaction *transcation) {
        [HUD hideFromViewAnimated:YES];
        if (transcation.error) {
            NSLog(@"Fail %@", [transcation.error localizedDescription]);
            //[self verifyPruchase];
        } else if (transcation.transactionState  ==  SKPaymentTransactionStatePurchased) {
            //[self verifyPruchase];
           [HUD setOnViewWithTitle:@"支付结果确认中" animated:YES];
            // 服务器验证支付是否成功
            NSData *transactionReceipt = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
           //NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:transactionReceipt options:1 error:nil];
            //NSLog(@"%@",dic);
            
            NSDictionary *verifyParams = @{
                                        @"receipt": [transactionReceipt base64EncodedStringWithOptions:0],
                                  @"rechargeMoney": rechargeMoney,
                                         @"userId": [MLUser currentUser].objectId};
            [AVCloud callFunctionInBackground:@"verifyIAPReceipt" withParameters:verifyParams block:^(id object, NSError *error) {
                [HUD hideFromViewAnimated:YES];
                if (!error) {
                    // TODO 提示充值成功
                    // 充值成功, 刷新用户
                    [[MLUser currentUser] refreshInBackgroundWithBlock:nil];
                    [HUD Prompt:@"充值成功"];
                } else {
                    [HUD Prompt:@"充值失败,请重试"];
                    NSLog(@"充值失败");
                }
            }];
            // 将交易从交易队列中删除
            [[SKPaymentQueue defaultQueue] finishTransaction:transcation];
        } else if (transcation.transactionState  ==  SKPaymentTransactionStateFailed) {
            [HUD Prompt:@"充值失败,请重试"];
        }
    }];
}


#pragma mark 验证购买凭据
- (void)verifyPruchase
{
    // 验证凭据，获取到苹果返回的交易凭据
    // appStoreReceiptURL iOS7.0增加的，购买交易完成后，会将凭据存放在该地址
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    // 从沙盒中获取到购买凭据
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    
    // 发送网络POST请求，对购买凭据进行验证
    NSURL *url = [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"];
    // 国内访问苹果服务器比较慢，timeoutInterval需要长一点
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    
    request.HTTPMethod = @"POST";
    
    // 在网络中传输数据，大多情况下是传输的字符串而不是二进制数据
    // 传输的是BASE64编码的字符串
    /**
     BASE64 常用的编码方案，通常用于数据传输，以及加密算法的基础算法，传输过程中能够保证数据传输的稳定性
     BASE64是可以编码和解码的
     */
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", encodeStr];
    NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
    
    request.HTTPBody = payloadData;
    
    // 提交验证请求，并获得官方的验证JSON结果
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    // 官方验证结果为空
    if (result == nil) {
        NSLog(@"验证失败");
    }
   
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
    
    NSLog(@"%@", dict);
    
    if (dict != nil) {
        // 比对字典中以下信息基本上可以保证数据安全
        // bundle_id&application_version&product_id&transaction_id
        NSLog(@"验证成功%@",dict);
    }
}

@end
